package com.qubuyer.business.good.viewmodel

import androidx.lifecycle.MutableLiveData
import com.qubuyer.core.anno.AutoInject
import com.qubuyer.core.framework.BaseViewModel
import com.qubuyer.core.http.RetrofitCall
import com.qubuyer.repository.entitys.*

class SOViewModel : BaseViewModel() {
    //购买类型 1:商品详情购买 2:购物车购买
    var buyType: Int = 0
    var goodsId: Int = 0
    var itemId: Int = 0
    var goodsNum: Int = 0

    val orderInfo = MutableLiveData<SOGoodInfoEntity>()

    val priceInfo = MutableLiveData<CalcOrderPriceResultEntity>()

    val addressInfo = MutableLiveData<MineAddressEntity?>()

    val resultInfo = MutableLiveData<GoodSOResultEntity>()

    val invoiceInfo = MutableLiveData<MineInvoiceEntity>()

    @AutoInject
    private val soModel = SOModel()

    fun getSOInfo() {
        RetrofitCall<SOGoodInfoEntity?>(lifecycleOwner, this) {
            api { if (buyType == 2) soModel.buyFromCart() else soModel.buyNow(goodsNum, goodsId, itemId) }
            success {
                orderInfo.value = it
                getDefaultAddress()
            }
        }
    }

    private fun getDefaultAddress() {
        RetrofitCall<List<MineAddressEntity>?>(lifecycleOwner, this) {
            api { soModel.addressList() }
            success {
                addressInfo.value = it?.firstOrNull()
            }
        }
    }

    fun calcOrderPrice(addressId: String) {
        RetrofitCall<CalcOrderPriceResultEntity?>(lifecycleOwner, this) {
            api { if (buyType == 2) soModel.priceCalculation(null, null, null, addressId) else soModel.priceCalculation(goodsNum, goodsId, itemId, addressId) }
            success {
                priceInfo.value = it
            }
        }
    }

    fun submitOrder(userNote: String) {
        RetrofitCall<GoodSOResultEntity?>(lifecycleOwner, this) {
            api {
                if (buyType == 2) soModel.buyFromCartPlace(
                        addressInfo.value?.address_id
                                ?: "",
                        addressInfo.value?.mobile ?: "", userNote,
                        invoiceInfo.value
                )
                else soModel.buyNowPlace(goodsNum, goodsId, itemId, addressInfo.value?.address_id
                        ?: "",
                        addressInfo.value?.mobile ?: "", userNote,
                        invoiceInfo.value)
            }
            success {
                resultInfo.value = it
            }
        }
    }

}